<script setup lang="ts">
import { ref, nextTick } from "vue";
import { useDeepSeek } from "@/utils/deepseek";
import { marked } from "marked";

const { sendMessage } = useDeepSeek();
const inputMsg = ref("");
const chatHistory = ref<any[]>([]);
const isLoading = ref(false);
const thinkingProcess = ref<string[]>([]);
const showThoughts = ref(false);

// 创建响应式变量用于跟踪当前消息
const currentMessageIndex = ref(-1);

const renderMarkdown = (text: string): string => {
  return marked.parse(text, { async: false }) as string;
};

const scrollToBottom = () => {
  nextTick(() => {
    const container = document.querySelector(".chat-container");
    if (container) {
      container.scrollTop = container.scrollHeight;
    }
  });
};

const handleSubmit = async () => {
  if (!inputMsg.value.trim() || isLoading.value) return;

  // 重置状态
  thinkingProcess.value = [];
  showThoughts.value = false;

  // 添加用户消息
  chatHistory.value.push({
    role: "user",
    content: inputMsg.value,
    timestamp: new Date().toISOString(),
  });

  // 添加AI消息占位符
  const aiMessage = {
    role: "assistant",
    content: "",
    thinking: [] as string[],
    timestamp: new Date().toISOString(),
  };

  chatHistory.value.push(aiMessage);
  
  // 设置当前消息索引
  currentMessageIndex.value = chatHistory.value.length - 1;

  isLoading.value = true;
  inputMsg.value = "";

  scrollToBottom();

  try {
    await sendMessage([...chatHistory.value], (data) => {
      const aiMessage = chatHistory.value[currentMessageIndex.value];
      if (!aiMessage) return;
      
      // 处理错误
      if (data.error) {
        aiMessage.content = `错误: ${data.error}`;
        if (data.content) {
          aiMessage.content += `\n原始数据: ${data.content}`;
        }
        isLoading.value = false;
        scrollToBottom();
        return;
      }

      // 处理结束标志
      if (data.finished) {
        isLoading.value = false;
        showThoughts.value = aiMessage.thinking.length > 0;
        scrollToBottom();
        return;
      }

      // 处理思考过程
      if (data.isThinking && data.content) {
        if (aiMessage.thinking.length === 0) {
          aiMessage.thinking.push(data.content);
        } else {
          // 追加到最后一段思考过程
          const lastIndex = aiMessage.thinking.length - 1;
          aiMessage.thinking[lastIndex] += data.content;
        }
        thinkingProcess.value = [...aiMessage.thinking];
      }
      // 处理最终回答
      else if (data.isAnswer && data.content) {
        aiMessage.content += data.content;
      }
      // 普通内容
      else if (data.content) {
        aiMessage.content += data.content;
      }
      
      // 每次更新后都滚动到底部
      scrollToBottom();
    });
  } catch (error: any) {
    console.error("Submit Error:", error);
    const aiMessage = chatHistory.value[currentMessageIndex.value];
    if (aiMessage) {
      aiMessage.content = `请求失败: ${error.message}`;
    }
    isLoading.value = false;
    scrollToBottom();
  }
};
</script>

<template>
  <div class="chat-container">
    <div
      v-for="(msg, index) in chatHistory"
      :key="index"
      class="message"
      :class="msg.role"
    >
      <div class="message-header">
        <strong>{{ msg.role === "user" ? "您" : "AI助手" }}</strong>
        <span class="timestamp">{{
          new Date(msg.timestamp).toLocaleTimeString()
        }}</span>
      </div>

      <div
        v-if="msg.role === 'assistant'"
        class="message-content"
        v-html="renderMarkdown(msg.content)"
      ></div>
      <div v-else class="message-content">{{ msg.content }}</div>

      <div
        v-if="msg.role === 'assistant' && msg.thinking?.length"
        class="thinking-indicator"
      >
        <span @click="showThoughts = !showThoughts" class="toggle-thoughts">
          查看思考过程 ({{ showThoughts ? "隐藏" : "显示" }})
        </span>
      </div>
    </div>

    <!-- 思考过程展示区域 -->
    <div v-if="showThoughts && thinkingProcess.length" class="thought-process">
      <div class="thought-process-header">
        <h3>思考过程</h3>
        <button @click="showThoughts = false" class="close-thoughts">×</button>
      </div>

      <div class="thought-steps">
        <div
          v-for="(thought, idx) in thinkingProcess"
          :key="idx"
          class="thought-step"
          v-html="renderMarkdown(thought)"
        ></div>
      </div>
    </div>

    <div class="input-area">
      <textarea
        v-model="inputMsg"
        placeholder="输入消息..."
        @keyup.enter.exact.prevent="handleSubmit"
        :disabled="isLoading"
      ></textarea>

      <button @click="handleSubmit" :disabled="isLoading">
        {{ isLoading ? "思考中..." : "发送" }}
      </button>
    </div>
  </div>
</template>

<style scoped>
/* 添加打字机动画效果 */
.message.assistant .message-content {
  white-space: pre-wrap;
}

.message.assistant .message-content >>> * {
  display: inline;
  animation: typing 0.1s steps(1, end);
}

@keyframes typing {
  from { opacity: 0; }
  to { opacity: 1; }
}

/* 其余样式保持不变 */
.chat-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  display: flex;
  flex-direction: column;
  height: 100vh;
  max-height: 100vh;
  overflow: hidden;
  background-color: #f5f7fa;
}

.message {
  margin-bottom: 20px;
  padding: 15px;
  border-radius: 12px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
  animation: fadeIn 0.3s ease;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.message.user {
  background-color: #e3f2fd;
  align-self: flex-end;
  max-width: 80%;
  border-bottom-right-radius: 4px;
}

.message.assistant {
  background-color: #ffffff;
  align-self: flex-start;
  max-width: 80%;
  border-bottom-left-radius: 4px;
}

.message-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  font-size: 0.9rem;
}

.timestamp {
  color: #6c757d;
  font-size: 0.8rem;
}

.message-content {
  line-height: 1.6;
}

.message-content >>> p {
  margin-bottom: 8px;
}

.message-content >>> code {
  background-color: #f1f1f1;
  padding: 2px 4px;
  border-radius: 4px;
  font-family: monospace;
}

.message-content >>> pre {
  background-color: #2d2d2d;
  color: #f8f8f2;
  padding: 10px;
  border-radius: 4px;
  overflow-x: auto;
}

.thinking-indicator {
  margin-top: 10px;
  font-size: 0.85rem;
}

.toggle-thoughts {
  color: #2196f3;
  cursor: pointer;
  text-decoration: underline;
}

.thought-process {
  margin-top: 20px;
  padding: 15px;
  background-color: #fffde7;
  border-radius: 12px;
  border-left: 4px solid #ffc107;
  animation: slideIn 0.3s ease;
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.thought-process-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.thought-process-header h3 {
  margin: 0;
  color: #ff9800;
}

.close-thoughts {
  background: none;
  border: none;
  font-size: 1.5rem;
  cursor: pointer;
  color: #ff9800;
}

.thought-steps {
  max-height: 300px;
  overflow-y: auto;
  padding-right: 10px;
}

.thought-step {
  margin: 12px 0;
  padding: 10px 15px;
  background: #fff8e1;
  border-radius: 8px;
  border-left: 3px solid #4caf50;
  animation: fadeIn 0.3s ease;
}

.input-area {
  margin-top: auto;
  padding-top: 20px;
  display: flex;
  gap: 10px;
}

textarea {
  flex: 1;
  padding: 12px 15px;
  border: 1px solid #ddd;
  border-radius: 8px;
  resize: none;
  min-height: 50px;
  font-family: inherit;
  font-size: 1rem;
}

textarea:focus {
  outline: none;
  border-color: #2196f3;
  box-shadow: 0 0 0 2px rgba(33, 150, 243, 0.2);
}

button {
  padding: 12px 24px;
  background-color: #2196f3;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-weight: 500;
  transition: background-color 0.2s;
  align-self: flex-end;
}

button:hover {
  background-color: #0b7dda;
}

button:disabled {
  background-color: #bbdefb;
  cursor: not-allowed;
}

@media (max-width: 768px) {
  .chat-container {
    padding: 10px;
  }

  .message.user,
  .message.assistant {
    max-width: 90%;
  }

  .input-area {
    flex-direction: column;
  }
}
</style>